﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTunesLib;

namespace Red_Mosquito
{
    class iTunesControl
    {
        public const int BACK = 0;
        public const int PLAY_PAUSE = 1;
        public const int FORWARD = 2;

        private iTunesApp iTunes;
        private Form1 form;
        public bool isPlaying;

        public iTunesControl(Form1 f)
        {
            // Connect Control to Form
            form = f;

            // Start/Connect to iTunes
            iTunes = new iTunesApp();

            // Register event listener
            iTunes.OnPlayerPlayEvent += new _IiTunesEvents_OnPlayerPlayEventEventHandler(iTunes_OnPlayerPlayEvent);
            iTunes.OnPlayerStopEvent += new _IiTunesEvents_OnPlayerStopEventEventHandler(iTunes_OnPlayerStopEvent);

            // Sync up isPlaying with iTunes status
            isPlaying = iTunes.PlayerState == ITPlayerState.ITPlayerStatePlaying;
        }

        void iTunes_OnPlayerStopEvent(object iTrack)
        {
            // Make sure isPlaying stays synced
            isPlaying = false;

            // If player is still stopped, update GUI
            update();
        }

        private void iTunes_OnPlayerPlayEvent(object iTrack)
        {
            // Make sure isPlaying stays synced
            isPlaying = true;

            // Update GUI
            update();
        }

        public void update()
        {
            // Get current track
            IITTrack current = iTunes.CurrentTrack;

            // Send track info to GUI
            if (current != null)
                form.nowPlaying(current.Name, current.Artist, current.Album);
            else
                form.nowPlaying("","","");
        }

        public void action(int type)
        {
            // Switch on which button is pressed
            switch (type)
            {
                case BACK:
                    iTunes.PreviousTrack();
                    break;
                case PLAY_PAUSE:
                    if (isPlaying)
                        iTunes.Pause();
                    else
                        iTunes.Play();
                    isPlaying = !isPlaying;
                    break;
                case FORWARD:
                    iTunes.NextTrack();
                    break;
                default:
                    break;
            }
        }
        
        public void disconnect()
        {
            // Remove any handlers from the iTunes COM object.
            iTunes.OnPlayerPlayEvent -= iTunes_OnPlayerPlayEvent;
            iTunes.OnPlayerStopEvent -= iTunes_OnPlayerStopEvent;
        }
    }
}
